// app/service/zcy_sync_service.js
'use strict';

const { Service } = require('egg');
const axios = require('axios');

class ZcySyncService extends Service {
  // 同步政采云订单数据
  async syncZcyOrders(options = {}) {
    const { ctx } = this;
    const { lastSyncTime } = options;
    
    try {
      const newOrders = [];
      const updatedOrders = [];
      let retryCount = 0;
      const maxRetries = 5;
      
      while (retryCount < maxRetries) {
        try {
          // 模拟调用政采云API
          const response = await this.callZcyApi('/api/orders', {
            lastSyncTime,
            page: 1,
            pageSize: 100
          });
          
          // 处理响应数据
          const { data, pagination } = response;
          
          for (const orderData of data) {
            const existingOrder = await ctx.model.SalesOrderModel.findOne({
              where: { platformOrderId: orderData.orderId }
            });
            
            if (existingOrder) {
              // 更新现有订单
              await existingOrder.update({
                orderStatus: orderData.status,
                invoiceStatus: orderData.invoiceStatus,
                updatedAt: new Date()
              });
              updatedOrders.push(existingOrder);
            } else {
              // 创建新订单
              const newOrder = await ctx.model.SalesOrderModel.create({
                platformOrderId: orderData.orderId,
                customerId: orderData.customerId,
                customerName: orderData.customerName,
                orderAmount: orderData.amount,
                orderStatus: orderData.status,
                orderDate: orderData.orderDate,
                invoiceStatus: orderData.invoiceStatus,
                responsibleSalesman: orderData.salesman
              });
              newOrders.push(newOrder);
            }
          }
          
          break; // 成功后退出重试循环
        } catch (error) {
          if (error.response && error.response.status === 429) {
            // 处理API限流
            retryCount++;
            if (retryCount >= maxRetries) {
              throw new Error(`达到最大重试次数 ${maxRetries}`);
            }
            
            // 等待后重试
            const waitTime = Math.pow(2, retryCount) * 1000; // 指数退避
            await this.sleep(waitTime);
          } else {
            throw error;
          }
        }
      }
      
      return {
        newOrders: newOrders.length,
        updatedOrders: updatedOrders.length,
        retryCount
      };
    } catch (error) {
      ctx.logger.error('同步政采云订单失败:', error);
      throw error;
    }
  }
  
  // 调用政采云API
  async callZcyApi(endpoint, params) {
    const { ctx } = this;
    
    try {
      // 检查配置是否存在
      // 在开发环境中，如果API密钥未设置，则跳过API调用
      if (!ctx.app.config.zcyApi || !ctx.app.config.zcyApi.baseUrl) {
        throw new Error('政采云API配置缺失，请检查config.default.js中的zcyApi配置');
      }
      
      // 在开发环境中，如果API密钥未设置或为空，则返回模拟数据
      if (!ctx.app.config.zcyApi.apiKey || ctx.app.config.zcyApi.apiKey === '' || ctx.app.config.zcyApi.apiKey === 'your_api_key_here') {
        ctx.logger.warn('政采云API密钥未配置，返回模拟数据');
        // 返回模拟数据
        return {
          data: [],
          pagination: {
            page: 1,
            pageSize: 100,
            total: 0
          }
        };
      }
      
      const response = await axios.get(`${ctx.app.config.zcyApi.baseUrl}${endpoint}`, {
        params,
        headers: {
          'Authorization': `Bearer ${ctx.app.config.zcyApi.apiKey}`,
          'User-Agent': 'Lingxi-Reconciliation-System/1.0'
        },
        timeout: 10000 // 10秒超时
      });
      
      return response.data;
    } catch (error) {
      if (error.response) {
        // API返回错误状态码
        ctx.logger.error(`政采云API错误 ${error.response.status}:`, error.response.data);
        throw error;
      } else if (error.request) {
        // 请求发送但无响应
        ctx.logger.error('政采云API无响应:', error.message);
        throw new Error('政采云API无响应');
      } else {
        // 请求配置错误
        ctx.logger.error('政采云API请求错误:', error.message);
        throw error;
      }
    }
  }
  
  // 处理API限流
  async handleRateLimit(apiCall) {
    let retryCount = 0;
    const maxRetries = 5;
    
    while (retryCount < maxRetries) {
      try {
        return await apiCall();
      } catch (error) {
        if (error.response && error.response.status === 429) {
          retryCount++;
          if (retryCount >= maxRetries) {
            throw new Error(`达到最大重试次数 ${maxRetries}`);
          }
          
          // 指数退避等待
          const waitTime = Math.pow(2, retryCount) * 1000;
          await this.sleep(waitTime);
        } else {
          throw error;
        }
      }
    }
  }
  
  // 等待指定时间
  sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
  
  // 等待订单状态变更
  async waitForStatusChange(orderId, expectedStatus, timeout = 60000) {
    const { ctx } = this;
    const startTime = Date.now();
    
    while (Date.now() - startTime < timeout) {
      const order = await ctx.model.SalesOrderModel.findByPk(orderId);
      if (order && order.orderStatus === expectedStatus) {
        return order;
      }
      
      // 等待1秒后重试
      await this.sleep(1000);
    }
    
    throw new Error(`订单 ${orderId} 在 ${timeout}ms 内未达到期望状态 ${expectedStatus}`);
  }
}

module.exports = ZcySyncService;